//
//  CustomLoginViewController.m
//  SoutheastAsia
//
//  Created by rimi on 16/1/16.
//  Copyright © 2016年 zlj. All rights reserved.
//

#import "CustomLoginViewController.h"
#import "AVOSCloud/AVOSCLoud.h"
#import "UserModel.h"
#import "ControllerManager.h"
#import "LEffectLabel.h"
#import "RegisterViewController.h"

@interface CustomLoginViewController () <UITextFieldDelegate>


@property (nonatomic, strong) UITextField *loginTextField;
@property (nonatomic, strong) UITextField *mmTextField;
@property (nonatomic, strong) UIButton *backLoginButton;
@property (nonatomic, strong) UIButton *loginButton;
@property (nonatomic, strong) UIImageView *backgroundImageView;
@property (nonatomic, strong) UIImageView *logoImageView;

@property (nonatomic, strong) LEffectLabel *registerLabel;
@property (nonatomic, strong) UISwipeGestureRecognizer *downGesture;
@property (nonatomic, strong) UIView *downView;
@property (nonatomic, strong) UIImageView *downImageView;


- (void)initializeApperance;
@end


@implementation CustomLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeApperance];

}

#pragma mark -- private method
- (void)initializeApperance {
    [self.view addSubview:self.backgroundImageView];
    [self.view addSubview:self.logoImageView];
    [self.view addSubview:self.backLoginButton];
    [self.view addSubview:self.loginTextField];
    [self.view addSubview:self.mmTextField];
    [self.view addSubview:self.loginButton];
    [self.view addSubview:self.downView];
    [self.downView addSubview:self.registerLabel];
    [self performSelector:@selector(addAnimation) withObject:nil afterDelay:5];

}

- (void)addAnimation
{
    
    for (int i = 0; i < 1000; i++)
    {
        int64_t delayInSeconds = 2 * i;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            self.registerLabel.effectDirection = EffectDirectionTopToBottom;
            [self.registerLabel performEffectAnimation];
        });
    }
}


#pragma mark -- callback / action
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)backLoginButtonTaped:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)isLoginTaped:(UIButton *)sender {
    
    if ([self.loginTextField.text isEqualToString:@""]) {
        UIAlertController *alertAction = [UIAlertController alertControllerWithTitle:@"" message:@"请输入用户名" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *exitAlert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alertAction addAction:exitAlert];
        [self presentViewController:alertAction animated:YES completion:nil];
        return;
    }
    if ([self.mmTextField.text isEqualToString:@""]) {
        UIAlertController *alertAction = [UIAlertController alertControllerWithTitle:@"" message:@"请输入密码" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *exitAlert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alertAction addAction:exitAlert];
        [self presentViewController:alertAction animated:YES completion:nil];
        return;
    }
    
        [AVUser logInWithUsernameInBackground:self.loginTextField.text password:self.mmTextField.text block:^(AVUser *user, NSError *error) {
            if (user != nil) {
                UIAlertController *alertAction = [UIAlertController alertControllerWithTitle:@"登陆成功" message:[NSString stringWithFormat:@"欢迎%@",self.loginTextField.text] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *exitAlert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    
                    [UserModel defaultUesr].userName = self.loginTextField.text;
                    [UserModel defaultUesr].userPassword = self.mmTextField.text;
                    // 登陆状态
                    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                    [userDefaults setObject:@"yes" forKey:@"isLogin"];
                    [userDefaults setObject:self.loginTextField.text forKey:@"userName"];
                    [userDefaults synchronize];
                    
                    [self dismissViewControllerAnimated:YES completion:nil];
                }];
                [alertAction addAction:exitAlert];
                [self presentViewController:alertAction animated:YES completion:nil];
            } else {
                UIAlertController *alertAction = [UIAlertController alertControllerWithTitle:@"登陆失败" message:@"用户名或密码错误" preferredStyle:UIAlertControllerStyleAlert];
    
                UIAlertAction *exitAlert = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    
                [alertAction addAction:exitAlert];
    
                [self presentViewController:alertAction animated:YES completion:nil];
            }
        }];
}
- (void)registerGestureTaped:(UISwipeGestureRecognizer *)gesture {
    RegisterViewController *registerVC = [[RegisterViewController alloc] init];
    registerVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:registerVC animated:YES completion:nil];
}
#pragma mark -- system protocol

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

//开始编辑输入框的时候，软键盘出现，执行此事件
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGRect frame = textField.frame;
    int offset = frame.origin.y + 32 - (self.view.frame.size.height - 300);//键盘高度300
    
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    //将视图的Y坐标向上移动offset个单位，以使下面腾出地方用于软键盘的显示
    if(offset > 0)
        self.view.frame = CGRectMake(0.0f, -offset, self.view.frame.size.width, self.view.frame.size.height);
    
    [UIView commitAnimations];
}

//输入框编辑完成以后，将视图恢复到原始状态
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame =CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [UIView commitAnimations];
}

#pragma mark -- getter
//登陆输入框
- (UITextField *)loginTextField {
    if (!_loginTextField) {
        _loginTextField = [[UITextField alloc] init];
        _loginTextField.bounds = CGRectMake(0, 0, 200, 40);
        _loginTextField.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMidY(self.view.frame) - 10);
        _loginTextField.layer.borderWidth = 1;
        _loginTextField.layer.cornerRadius = 15;
        _loginTextField.borderStyle = UITextBorderStyleRoundedRect;
        _loginTextField.placeholder = @"请输入登录名";
        _loginTextField.leftView =  [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, 0)];
        _loginTextField.leftViewMode = UITextFieldViewModeAlways;
        _loginTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _loginTextField.delegate = self;
        _loginTextField.keyboardType = UIKeyboardTypeNamePhonePad;

    }
    return _loginTextField;
}
//密码输入框
- (UITextField *)mmTextField {
    if (!_mmTextField) {
        _mmTextField = [[UITextField alloc] init];
        _mmTextField.bounds = CGRectMake(0, 0, 200, 40);
        _mmTextField.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMidY(self.view.frame) + 50);
        _mmTextField.placeholder = @"请输入密码";
        _mmTextField.borderStyle = UITextBorderStyleRoundedRect;
        _mmTextField.leftView =  [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, 0)];
        _mmTextField.leftViewMode = UITextFieldViewModeAlways;
        _mmTextField.layer.borderWidth = 1;
        _mmTextField.layer.cornerRadius = 15;
        _mmTextField.secureTextEntry = YES;
        _mmTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _mmTextField.delegate = self;
    }
    return _mmTextField;
}
- (UIButton *)backLoginButton {
    if (!_backLoginButton) {
        _backLoginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _backLoginButton.frame = CGRectMake(5, 40, 40, 40);
        [_backLoginButton setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
        [_backLoginButton addTarget:self action:@selector(backLoginButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backLoginButton;
}
//登陆按钮
- (UIButton *)loginButton {
    if (!_loginButton) {
        _loginButton = ({
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.bounds = CGRectMake(0, 0, 140, 80);
            button.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMidY(self.view.frame) + 130);
            [button setTitle:@"Sign in" forState:UIControlStateNormal];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [button.titleLabel setTextAlignment:NSTextAlignmentCenter];
            [button.titleLabel setFont:[UIFont fontWithName:@"Georgia" size:30]];
            [button addTarget:self action:@selector(isLoginTaped:) forControlEvents:UIControlEventTouchUpInside];
            button;
        });
    }
    return _loginButton;
}
//background
- (UIImageView *)backgroundImageView {
    if (!_backgroundImageView) {
        _backgroundImageView = ({
            UIImageView *view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loginbackground.png"]];
            view.frame = CGRectMake(0, 0, CGRectGetMaxX(self.view.frame), CGRectGetMaxY(self.view.frame));
            view;
        });
    }
    return _backgroundImageView;
}
//logo
- (UIImageView *)logoImageView {
    if (!_logoImageView) {
        _logoImageView = ({
            UIImageView *view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"title.png"]];
            view.bounds = CGRectMake(0, 0, CGRectGetMaxX(self.view.bounds), 400);
            view.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds) - 70);
            
            view;
        });
    }
    return _logoImageView;
}
//注册
- (LEffectLabel *)registerLabel {
    if (!_registerLabel) {
        _registerLabel = ({
            
            LEffectLabel *label = [[LEffectLabel alloc] initWithFrame:CGRectMake(0, 0, 200, 120)];
            label.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
            
            [label setTextColor:[UIColor whiteColor]];
            label.effectColor = [UIColor blackColor];
            [label setBackgroundColor:[UIColor redColor]];
            [label setText:@"Register"];
            [label setFont:[UIFont fontWithName:@"Georgia" size:30]];
            label.userInteractionEnabled = YES;
            label.center = CGPointMake(100, 50);
            
            label;
        });
    }
    return _registerLabel;
}
//注册手势
- (UISwipeGestureRecognizer *)downGesture {
    if (!_downGesture) {
        _downGesture = ({
            UISwipeGestureRecognizer *gesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(registerGestureTaped:)];
            gesture.direction = UISwipeGestureRecognizerDirectionDown;
            gesture;
        });
    }
    return _downGesture;
}
- (UIView *)downView {
    if (!_downView) {
        _downView = ({
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 100)];
            view.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMaxY(self.view.frame) - 60);
            view.backgroundColor = [UIColor clearColor];
            [view addSubview:self.registerLabel];
            [view addSubview:self.downImageView];
            [view addGestureRecognizer:self.downGesture];
            
            view;
        });
    }
    return _downView;
}
- (UIImageView *)downImageView {
    if (!_downImageView) {
        _downImageView = ({
            UIImageView *view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"箭头.png"]];
            view.bounds = CGRectMake(0, 0, 64, 40);
            view.center = CGPointMake(100, 80);
            view;
        });
    }
    return _downImageView;
}
@end
